package com.flower.subject.domain.service.impl;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.flower.subject.domain.convent.SubjectInfoConverter;
import com.flower.subject.domain.convent.SubjectLabelConverter;
import com.flower.subject.domain.entity.SubjectCategoryBO;
import com.flower.subject.domain.entity.SubjectInfoBO;
import com.flower.subject.domain.entity.SubjectLabelBO;
import com.flower.subject.domain.entity.SubjectOptionBO;
import com.flower.subject.domain.handler.subject.SubjectTypeHandler;
import com.flower.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.flower.subject.domain.redis.RedisUtil;
import com.flower.subject.domain.service.SubjectInfoDomainService;
import com.flower.subject.domain.service.SubjectLabelDomainService;
import com.flower.subject.domain.service.SubjectLikedDomainService;
import com.flower.subject.entity.PageResult;
import com.flower.subject.enums.IsDeletedFlagEnum;
import com.flower.subject.infra.basic.entity.*;
import com.flower.subject.infra.basic.service.SubjectEsService;
import com.flower.subject.infra.basic.service.SubjectInfoService;
import com.flower.subject.infra.basic.service.SubjectLabelService;
import com.flower.subject.infra.basic.service.SubjectMappingService;
import com.flower.subject.infra.rpc.UserRpc;
import com.flower.subject.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lavender
 * @version 1.0
 * @date 2024-07-03 11:30
 */

@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private UserRpc userRpc;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";



    /**
     * 工厂模式+策略模式
     * @param bo
     */
    @Override
    public void add(SubjectInfoBO bo) {

        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANT.convertBOtoInfo(bo);
        subjectInfo.setIsDelete(IsDeletedFlagEnum.UN_DELETED.getCode());
        SubjectInfo insert = subjectInfoService.insert(subjectInfo);
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        bo.setId(insert.getId());
        handler.add(bo);

        List<Integer> categoryIds = bo.getCategoryIds();
        List<Integer> labelIds = bo.getLabelIds();
        List<SubjectMapping> mappingList = new ArrayList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId->{
                SubjectMapping mapping = new SubjectMapping();
                mapping.setCategoryId(Long.valueOf(categoryId));
                mapping.setSubjectId(String.valueOf(subjectInfo.getId()));
                mapping.setLabelId(Long.valueOf(labelId));
                mappingList.add(mapping);
            });
        });

        subjectMappingService.batchInsert(mappingList);
        // 同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(System.currentTimeMillis());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectAnswer(bo.getSubjectAnswer());
        subjectInfoEs.setCreateTime(System.currentTimeMillis());
        subjectInfoEs.setCreateUser("测试");
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());
        subjectEsService.insert(subjectInfoEs);

        // redis放入zadd计入排行榜
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(),1);

    }

    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> page = new PageResult<>();
        page.setPageNo(subjectInfoBO.getPageNo());
        page.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANT.convertBOtoInfo(subjectInfoBO);

        int count = subjectInfoService.countByCondition(
                subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId());

        if(count == 0){
            return page;
        }

        List<SubjectInfo> subjectInfos =subjectInfoService.queryPage(subjectInfo,subjectInfoBO.getCategoryId(),
                subjectInfoBO.getLabelId(),
                start,
                subjectInfoBO.getPageSize());

        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.INSTANT.convertInfoToBOList(subjectInfos);
        page.setRecords(subjectInfoBOS);
        page.setTotal(count);

        return page;
    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        Integer subjectType = subjectInfo.getSubjectType();
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectType);
        SubjectOptionBO option = handler.query(subjectInfo.getId().intValue());
        SubjectInfoBO bo = SubjectInfoConverter.INSTANT.convertOptionAndInfotoBO(option,subjectInfo);
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfoBO.getId() + "");
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabels = subjectLabelService.batchQueryById(labelList);
        List<String> labelName  = subjectLabels.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());




        bo.setLabelName(labelName);

        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId() + "",LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getCount(subjectInfoBO.getId() + ""));


        assembleSubjectCursor(subjectInfoBO,bo);

        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        // 题目Id
        Long subjectId = subjectInfoBO.getId();

        if(Objects.isNull(categoryId) || Objects.isNull(labelId)){
            return;
        }

        Long nextSubjectId =  subjectInfoService.querySubjectIdCursor(subjectId,categoryId,labelId,1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId =  subjectInfoService.querySubjectIdCursor(subjectId,categoryId,labelId,0);
        bo.setLastSubjectId(lastSubjectId);
    }

    @Override
    public List<SubjectInfoBO> getContributeList() {
        List<SubjectInfo> subjectInfos =  subjectInfoService.getContributeCount();
        List<SubjectInfoBO> boList = new LinkedList<>();
        subjectInfos.forEach(subjectInfo -> {
            SubjectInfoBO bo = new SubjectInfoBO();
            bo.setSubjectCount(subjectInfo.getSubjectCount());

        boList.add(bo);
        });

        // redis 获取排行榜
//        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);


        return boList;
    }


}
